package br.com.fiap.trabalho.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import br.com.fiap.trabalho.entity.Studio;

public class JDBCStudioDAO implements StudioDAO{

	private Connection cn;
	private PreparedStatement ps;
	private ResultSet rs;
	private Studio studio = null;
	
	public JDBCStudioDAO(Studio studio) {
		this.studio = studio;
	}

	private boolean abreConexao() throws Exception{
		try{
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
			String url = "jdbc:derby:simpleDB;create=true";
			cn = DriverManager.getConnection(url,"TrabalhoPersistenciaJava","TrabalhoPersistenciaJava");
			return true;
		}
		catch(Exception ex){
			throw ex;
		}
	}


	public Studio createStudio() {

		try {

			//studio.setId(0);
			//studio.setName("Studio1");
			abreConexao();
			cn.setAutoCommit(false);

			ps = cn.prepareStatement("INSERT INTO STUDIO (NAME) VALUES (?)", 
					Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, studio.getName());
			ps.executeUpdate();
			ResultSet rs = ps.getGeneratedKeys();
			if(rs.next()) 
			{
				studio.setId( rs.getInt(1));
			}
			
			cn.commit();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				cn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		finally{
			try {
				cn.setAutoCommit(true);
				ps.close();
				cn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return studio;
	}


	public List<Studio> selectStudioByName(String name) {
		List<Studio> listStudio = new ArrayList<Studio>();

		try {
			abreConexao();
			ps = cn.prepareStatement("SELECT ID_STUDIO, NAME FROM STUDIO WHERE NAME = ?");
			ps.setString(1, name);
			rs = ps.executeQuery();

			Studio studio;
			while (rs.next()) {
				studio = new Studio();
				studio.setId(rs.getInt(1));
				studio.setName(rs.getString(2));
				listStudio.add(studio);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				ps.close();
				cn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return listStudio;
	}

	public Studio getStudio() {
		return studio;
	}

	public void setStudio(Studio studio) {
		this.studio = studio;
	}
}